﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace JsonEditor.Utils
{
    /// <summary>
    /// 序列化
    /// </summary>
    public class SerializeHelper
    {
        /// <summary>
        /// 对象序列化成XML
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string SerializeToXml(Object obj)
        {
            if (obj != null)
            {
                XmlSerializer s = new XmlSerializer(obj.GetType());
                StringBuilder stringBuilder = new StringBuilder();
                using (StringWriter writer = new StringWriter(stringBuilder))
                {
                    s.Serialize(writer, obj);
                }
                return stringBuilder.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 从XML反序列化成对象
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="xmlData">字符串</param>
        /// <returns></returns>
        public static T DeserializeFromXml<T>(string xmlData)
        {
            if (!string.IsNullOrEmpty(xmlData))
            {
                XmlSerializer s = new XmlSerializer(typeof(T));
                T entity = default(T);
                using (TextReader reader = new StringReader(xmlData))
                {
                    entity = (T)s.Deserialize(reader);
                    reader.Close();
                }
                return entity;
            }
            else
            {
                return default(T);
            }
        }

        /// <summary>
        /// 序列化成二进制字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string SerializeToBinaryString(Object obj)
        {
            string result = null;
            if (obj != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(ms, obj);
                    result = Convert.ToBase64String(ms.ToArray());
                }
            }
            return result;
        }

        /// <summary>
        /// 反序列化二进制字符串成对象
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="binaryData">字符串</param>
        /// <returns></returns>
        public static T DeserializeFromBinaryString<T>(string binaryData)
        {
            T result = default(T);
            if (!string.IsNullOrEmpty(binaryData))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    byte[] bytes = Convert.FromBase64String(binaryData);
                    ms.Write(bytes, 0, bytes.Length);
                    ms.Seek(0, System.IO.SeekOrigin.Begin);
                    result = (T)formatter.Deserialize(ms);
                }
            }
            return result;
        }

        #region
        /// <summary>
        /// json序列化（非二进制方式）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string SerializeObject<T>(T t)
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            return jsonSerialize.Serialize(t);
        }

        /// <summary>
        /// json反序列化（非二进制方式）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T DeserializeObject<T>(string jsonString)
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            return (T)jsonSerialize.Deserialize<T>(jsonString);
        }


        /// <summary>
        /// JSON序列化(二进制方式，实体类使用[Serializable])
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string SerializeObjectIO<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                ser.WriteObject(ms, t);
                string jsonString = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return jsonString;
            }
        }

        /// <summary>
        /// JSON反序列化(二进制方法，实体类使用[Serializable])
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T DeserializeObjectIO<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                T obj = (T)ser.ReadObject(ms);
                return obj;
            }
        }
        #endregion
    }
}
